#!/bin/bash

echo "Executing script by: caozhenho 24055060153"
echo "-----------------------------------------"


# Set your gender, M for male, F for female
MY_GENDER="M"

# Student folder created in script 1
SOURCE_DIR="students"


# Step 1: Check if the directory exists
if [ ! -d "$SOURCE_DIR" ]; then
    echo "Error: Directory '$SOURCE_DIR' not found!"
    exit 1
fi

# Step 2: Navigate to the student folder
cd "$SOURCE_DIR"

# Initialize total score and counter
total_average_score=0.0
student_count=0

# Set the full gender name for output
if [ "$MY_GENDER" = "M" ]; then
    gender_full_name="male(M)"
else
    gender_full_name="female(F)"
fi

echo "Calculating average score for all '$MY_GENDER' students..."

# Step 3: Traverse all student files ending with .txt
for file in *.txt; do
    
    # Step 4: Extract the gender from the file
    gender=$(grep "gender:" "$file" | cut -d' ' -f2)
    
    # Check if the gender matches
    if [ "$gender" = "$MY_GENDER" ]; then
        # Extract the average score
        average=$(grep "average:" "$file" | cut -d' ' -f2)
        
        # Accumulate average score and count
        total_average_score=$(echo "scale=2; $total_average_score + $average" | bc)
        student_count=$((student_count + 1))
        
        echo "Found $gender student: $file with average $average"
    fi
    
done

# Step 5: Calculate the final average score
final_average=$(echo "scale=1; $total_average_score / $student_count" | bc)
echo "-----------------------------------------"
echo "Total students found: $student_count"
echo "Average score of $gender_full_name: $final_average"